<?php
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}
session_start();
require_once '../config.php';

// 如果已经登录，跳转到管理后台
if (isset($_SESSION['admin_id'])) {
    header('Location: index.php');
    exit;
}


// 获取系统设置
$settings = getSettings();
$error = '';

// 处理登录请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $captcha = strtolower($_POST['captcha'] ?? '');
    $remember = isset($_POST['rememberme']);
    
    // 验证验证码
    if (empty($captcha) || !isset($_SESSION['captcha']) || $captcha !== $_SESSION['captcha']) {
        $error = '验证码错误';
    } elseif (empty($username) || empty($password)) {
        $error = '请输入用户名和密码';
    } else {
        try {
            $stmt = $pdo->prepare("SELECT * FROM admins WHERE username = ?");
            $stmt->execute([$username]);
            $admin = $stmt->fetch();
            
            if ($admin && password_verify($password, $admin['password'])) {
                $_SESSION['admin_id'] = $admin['id'];
                $_SESSION['admin_username'] = $admin['username'];
                
                // 处理自动登录
                if ($remember) {
                    $expire = time() + 60 * 60 * 24 * 5; // 5天
                    setcookie('admin_remember', $admin['id'] . '|' . md5($admin['password'] . $_SERVER['HTTP_USER_AGENT']), $expire, '/');
                }
                
                header('Location: index.php');
                exit;
            } else {
                $error = '用户名或密码错误';
            }
        } catch (PDOException $e) {
            $error = '登录失败：' . $e->getMessage();
        }
    }
    
    // 刷新验证码
    unset($_SESSION['captcha']);
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title><?php echo htmlspecialchars($settings['title']); ?> - 登录</title>
    <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
    <style>
        .signin-form .has-feedback {
            position: relative;
        }
        .signin-form .has-feedback .form-control {
            padding-left: 36px;
        }
        .signin-form .has-feedback .mdi {
            position: absolute;
            top: 0;
            left: 0;
            right: auto;
            width: 36px;
            height: 36px;
            line-height: 36px;
            z-index: 4;
            color: #dcdcdc;
            display: block;
            text-align: center;
            pointer-events: none;
        }
        .signin-form .has-feedback.row .mdi {
            left: 15px;
        }
    </style>
</head>

<body class="center-vh" style="background-image: url(http://shanhe.kim/api/wz/bing.php); background-size: cover;">
<div class="card card-shadowed p-5 mb-0 mr-2 ml-2">
    <div class="text-center mb-3">
        <a href="index.php">
            <img alt="<?php echo htmlspecialchars($settings['title']); ?>" src="../assets/images/logo-sidebar.png">
        </a>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger">
            <i class="mdi mdi-alert-circle-outline"></i> <?php echo $error; ?>
        </div>
    <?php endif; ?>

    <form action="" method="post" class="signin-form needs-validation" novalidate>
        <div class="mb-3 has-feedback">
            <span class="mdi mdi-account" aria-hidden="true"></span>
            <input type="text" class="form-control" name="username" placeholder="用户名" required>
        </div>

        <div class="mb-3 has-feedback">
            <span class="mdi mdi-lock" aria-hidden="true"></span>
            <input type="password" class="form-control" name="password" placeholder="密码" required>
        </div>
        
        <div class="mb-3 has-feedback row">
            <div class="col-7">
                <span class="mdi mdi-check-all form-control-feedback" aria-hidden="true"></span>
                <input type="text" name="captcha" class="form-control" placeholder="验证码" required>
            </div>
            <div class="col-5 text-right">
                <img src="captcha.php" class="pull-right" id="captcha" style="cursor: pointer; height: 36px;" onclick="this.src='captcha.php?d='+Math.random();" title="点击刷新" alt="captcha">
            </div>
        </div>

        <div class="mb-3">
            <div class="form-check">
                <input type="checkbox" class="form-check-input" id="rememberme" name="rememberme">
                <label class="form-check-label not-user-select" for="rememberme">5天内自动登录</label>
            </div>
        </div>

        <div class="mb-3 d-grid">
            <button class="btn btn-primary" type="submit">立即登录</button>
        </div>
    </form>
    
    <p class="text-center text-muted mb-0">Copyright © <?php echo date('Y'); ?> <a href="index.php"><?php echo htmlspecialchars($settings['title']); ?></a>. All right reserved</p>
</div>

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript" src="../assets/js/popper.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/lyear-loading.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap-notify.min.js"></script>
<script type="text/javascript">
var loader;
$(document).ajaxStart(function(){
    $("button:submit").html('登录中...').attr("disabled", true);
    loader = $('button:submit').lyearloading({
        opacity: 0.2,
        spinnerSize: 'nm'
    });
}).ajaxStop(function(){
    loader.destroy();
    $("button:submit").html('立即登录').attr("disabled", false);
});

$('.signin-form').on('submit', function(event) {
    if ($(this)[0].checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
        $(this).addClass('was-validated');
        return false;
    }
});

// 点击验证码图片刷新
$('#captcha').click(function() {
    $(this).attr('src', 'captcha.php?r=' + Math.random());
});
</script>
</body>
</html> 